import { ref, reactive, toRefs } from 'vue'
// 导入 elementUI 的 message 弹框
import { ElMessage } from 'element-plus'
// 导入 pinia 的仓库
import { useUserStore } from '@/stores/useUserStore.js'
// 导入 axios
import axios from 'axios'
const UserStore = useUserStore()

// 控制 dialog 的显隐
const dialogVisible = ref(false)
// 定义校验规则
const ruleFormRef = ref()
// 定义双向绑定的值
const ruleForm = reactive({
  region: '碰撞',
  address: '',
  sign: '',
  time: '',
  desc: ''
})
// 填写空字段的校验提示
const rules = reactive({
  region: [
    {
      required: true,
      message: '请选择事件类型',
      trigger: 'change'
    }
  ],
  address: [{ required: true, message: '请填写事发地址', trigger: 'blur' }],
  sign: [{ required: true, message: '请填写实地建筑标志', trigger: 'blur' }],
  time: [
    {
      type: 'date',
      required: true,
      message: '请选择日期和时间',
      trigger: 'change'
    }
  ],
  desc: [{ required: true, message: '请填写事件的详细信息', trigger: 'blur' }]
})
// 点击提交的回调
const handleSubmit = async (formEl, ruleForm) => {
  let { region, address, sign, time, desc } = ruleForm
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      dialogVisible.value = false
      formEl.resetFields()
      // 获取当前用户的 user_id
      let user_id = UserStore.userId
      // 把报告路况添加到数据库
      axios.post(`http://localhost:3000/ggevent`, {
        "user_id": user_id,
        "event_type": region,
        "event_addr": address,
        "event_mark": sign,
        "event_time": time,
        "event_describe": desc,
        "event_status": 0
      }).then(res => {
        ElMessage({
          type: 'success',
          message: '提交成功!'
        })
      })
    } else {
      ElMessage({
        type: 'error',
        message: '提交失败!存在未填写字段!'
      })
    }
  })
}
// 点击取消的回调
const handleCancel = (formEl) => {
  formEl.resetFields()
  dialogVisible.value = false
}

export { dialogVisible, ruleFormRef, rules, ruleForm, handleSubmit, handleCancel }